package com.example.goband.Config;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 22479
 * Date: 2023-06-01
 * Time: 20:37
 */

import com.example.goband.common.AjaxResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 默认统一数据格式返回
 */
public class ResponseAdvice implements ResponseBodyAdvice {


    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return false;
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        //如果已经主动设置统一数据格式返回,直接返回
        if(body instanceof AjaxResult) {
            return body;
        }
        //解决一下String问题
        if(body instanceof String) {
            return objectMapper.writeValueAsString(body);
        }
        //程序帮忙设置统一返回值
        return AjaxResult.success(body);
    }
}
